//
//  ZYPlayingViewController.m
//  ZYMusicPlayer
//
//  Created by 王志盼 on 15/10/13.
//  Copyright © 2015年 王志盼. All rights reserved.
//

#import "ZYPlayingViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "ZYMusicTool.h"
#import "BLETransDeviceSingleton.h"
#import "ZYAudioManager.h"
#import "ZYLrcView.h"
#import "UIView+AutoLayout.h"
#import <MediaPlayer/MediaPlayer.h>

@interface ZYPlayingViewController ()  <AVAudioPlayerDelegate>

@property (nonatomic, strong) MPMediaItem *musicItem;

@property (nonatomic, strong) ZYMusic *playingMusic;

/**
 *  显示播放进度条的定时器
 */
@property (nonatomic, strong) NSTimer *timer;
/**
 *  判断歌曲播放过程中是否被电话等打断播放
 */
@property (nonatomic, assign) BOOL isInterruption;

@property (nonatomic, weak) ZYLrcView *lrcView;
/**
 *  歌手图片
 */
@property (strong, nonatomic) IBOutlet UIImageView *iconView;

/**
 *  歌曲进度颜色背景
 */
@property (weak, nonatomic) IBOutlet UIView *progressView;


@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet UIView *topView;

@property (weak, nonatomic) IBOutlet UIButton *exitBtn;
@property (weak, nonatomic) IBOutlet UIButton *lyricOrPhotoBtn;
@property (strong, nonatomic) MPMusicPlayerController *mpc;
@end

@implementation ZYPlayingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.mpc = [[ZYAudioManager defaultManager] mpcVC];
    
    [self changeViewStyle];
    [self addNotification];
    [self beastStyle:NO];
    
    [self.playMixBtn setImage:[UIImage imageNamed:@"随机_Pre"] forState:UIControlStateNormal];
    [self.playMixBtn setImage:[UIImage imageNamed:@"随机"] forState:UIControlStateSelected];
    [self.replayBtn setImage:[UIImage imageNamed:@"循环_Pre"] forState:UIControlStateNormal];
    [self.replayBtn setImage:[UIImage imageNamed:@"循环"] forState:UIControlStateSelected];
    self.replayBtn.selected = YES;
    self.beastSwitch.on = YES;
    [self beastStyle:YES];
}

- (void)reload
{
   __block MPMediaItem *item = [ZYAudioManager defaultManager].mpcVC.nowPlayingItem;
    [[ZYMusicTool musics] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ZYMusic *music = obj;
        if (music.item == item) {
            self.playingMusic = music;
            self.musicItem = item;
            *stop = YES;
        }
    }];
    [self showPlayingView];
}

- (void)beastStyle:(BOOL)beast
{
    UInt8 data[3];
    data[0] = 0x7E;
    data[1] = beast ? 0x01 : 0x00;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:EQ_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}

- (void)changeViewStyle
{
    [self.timeSlider sliderTouchImage:[UIImage imageNamed:@"Oval1.png"] whitSize:CGSizeMake(10, 10)];
    self.timeSlider.minimumTrackTintColor = kAppNormalTextColor;
    self.timeSlider.maximumTrackTintColor = kAppNormalTextColor;
    [self.volSlider sliderTouchImage:[UIImage imageNamed:@"Oval2.png"] whitSize:CGSizeMake(25, 25)];
    self.volSlider.minimumTrackTintColor = kAppNormalTextColor;
    self.volSlider.maximumTrackTintColor = kAppNormalTextColor;
    
    self.beastSwitch.onTintColor = kAppSwitchOnCloor;
    self.beastSwitch.tintColor = kAppSwitchOnCloor;
    [self.playOrPauseButton setImage:[UIImage imageNamed:@"start"] forState:UIControlStateNormal];
    [self.playOrPauseButton setImage:[UIImage imageNamed:@"停止"] forState:UIControlStateSelected];
}

#pragma mark -  notification
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volNotication:) name:SOUNDS_CHARACTERISTIC_UUID object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil];
}

-(void)volNotication:(NSNotification *)notification
{
    NSData *data = notification.userInfo[kAppHeadUnitData];
    Byte *MessageBt = (Byte *)[data bytes];
    NSInteger type = MessageBt[0];
    if (type == 1) {
        NSInteger volNumber = MessageBt[2];
        NSLog(@"the vol is %ld", (long)volNumber);
        self.volSlider.value = volNumber * 0.08333;
    }
}
#pragma mark ----setup系列方法

#pragma mark ----音乐控制
- (void)musicBegin:(ZYMusic *)music
{
    [self removeCurrentTimer];
    self.playingMusic = music;
    [[ZYAudioManager defaultManager] playingMusic:music.item];
    [self showPlayingView];
    [self updateLockedScreenMusic];
}
//重置播放的歌曲
- (void)resetPlayingMusic
{
    // 重置界面数据
    self.iconView.image = [UIImage imageNamed:@"play_cover_pic_bg"];
    self.subNameLabel.text = nil;
    self.nameLabel.text = nil;
    self.playTimeLabel.text = [self stringWithTime:0];
    self.timeSlider.lx_x = 0;
    self.progressView.lx_width = self.timeSlider.center.x;
//    [self.timeSlider setTitle:[self stringWithTime:0] forState:UIControlStateNormal];
    
    //停止播放音乐
    [[ZYAudioManager defaultManager] stopMusic];
    [self removeCurrentTimer];
    [self musicBegin:self.playingMusic];
}

- (IBAction)timeChange:(UISlider *)sender {
    self.playTimeLabel.text = [self stringWithTime:sender.value * self.playingMusic.item.playbackDuration];
}
- (IBAction)timeDragEnter:(UISlider *)sender {
    [self removeCurrentTimer];
}

- (IBAction)timeDragExit:(UISlider *)sender {
    self.mpc.currentPlaybackTime = sender.value * [[self.playingMusic.item valueForProperty:MPMediaItemPropertyPlaybackDuration] doubleValue];
    [self addCurrentTimer];
}

- (IBAction)volDragExit:(UISlider *)sender {
    NSInteger number = sender.value / 0.08333;
    CGFloat last = sender.value - 0.08333 * number;
    if (last >= 0.0416) {
        number += 1;
    }
    
    UInt8 data[3];
    data[0] = 0x01;
    data[1] = number & 0xFF;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:SOUNDS_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}

- (IBAction)volChange:(UISlider *)sender {
}

- (IBAction)playMax:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [ZYAudioManager defaultManager].mpcVC.shuffleMode = sender.isSelected ? MPMusicShuffleModeSongs : MPMusicShuffleModeOff;
}

- (IBAction)upDown:(UIButton *)sender {
    [self removeCurrentTimer];
    [self addCurrentTimer];
    [[ZYAudioManager defaultManager] preMusic];
}

- (IBAction)playDown:(UIButton *)sender {
    if (self.playOrPauseButton.isSelected == NO) {
        self.playOrPauseButton.selected = YES;
        [self addCurrentTimer];
    } else{
        self.playOrPauseButton.selected = NO;
        [self removeCurrentTimer];
    }
    [[ZYAudioManager defaultManager] playPauseMusic];
}

- (IBAction)nextDown:(UIButton *)sender {
    [self removeCurrentTimer];
    [self addCurrentTimer];
    [[ZYAudioManager defaultManager] nextMusic];
}

- (IBAction)replayDown:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    [ZYAudioManager defaultManager].mpcVC.repeatMode = sender.isSelected ? MPMusicRepeatModeAll : MPMusicRepeatModeNone;
}

- (IBAction)beastDown:(UISwitch *)sender {
    if (sender.isOn) {
        [self beastStyle:YES];
    } else {
        [self beastStyle:NO];
    }
}

//开始播放音乐
- (void)showPlayingView
{
    [self getCommonValue];
    [self addCurrentTimer];
    self.iconView.image = self.playingMusic.icon;
    self.nameLabel.text = self.playingMusic.name;
    self.subNameLabel.text = self.playingMusic.singer;
    //self.player.delegate = self;
    self.totalTimeLabel.text = self.playingMusic.time;
    MPMusicPlayerController *mpc = [MPMusicPlayerController applicationMusicPlayer];
    MPMusicPlaybackState state = [mpc playbackState];
    if (state == MPMusicPlaybackStatePlaying) {
        self.playOrPauseButton.selected = YES;
    } else {
        self.playOrPauseButton.selected = NO;
    }
}

#pragma mark ----进度条定时器处理
/**
 *  添加定时器
 */
- (void)addCurrentTimer
{
    //在新增定时器之前，先移除之前的定时器
    [self removeCurrentTimer];
    [self updateCurrentTimer];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCurrentTimer) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

/**
 *  移除定时器
 */
- (void)removeCurrentTimer
{
    [self.timer invalidate];
    self.timer = nil;
}

/**
 *  触发定时器
 */
- (void)updateCurrentTimer
{
    double temp = self.mpc.currentPlaybackTime / [[self.playingMusic.item valueForProperty:MPMediaItemPropertyPlaybackDuration] doubleValue];
    self.timeSlider.value = temp;
    self.playTimeLabel.text = [self stringWithTime:self.mpc.currentPlaybackTime];
}

#pragma mark ----私有方法
- (void)getCommonValue {
    UInt8 data[3];
    data[0] = 0x01;
    data[1] = 0x01;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:COMMON_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}

/**
 *  将时间转化为合适的字符串
 *
 */
- (NSString *)stringWithTime:(NSTimeInterval)time
{
    int minute = time / 60;
    int second = (int)time % 60;
    return [NSString stringWithFormat:@"%02d:%02d",minute, second];
}


/**
 *  将控制器退下
 *
 */
- (IBAction)exit:(id)sender {
    [self removeCurrentTimer];
    if (self.delegate && [self.delegate respondsToSelector:@selector(playingViewControllerExit:)]) {
        [self.delegate playingViewControllerExit:self];
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
    }];
}

#pragma mark ----AVAudioPlayerDelegate

#pragma mark ----锁屏时候的设置，效果需要在真机上才可以看到
- (void)updateLockedScreenMusic
{
    // 播放信息中心
    MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
    // 初始化播放信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    // 专辑名称
    info[MPMediaItemPropertyAlbumTitle] = self.playingMusic.name;
    // 歌手
    info[MPMediaItemPropertyArtist] = self.playingMusic.singer;
    // 歌曲名称
    info[MPMediaItemPropertyTitle] = self.playingMusic.name;
    // 设置图片
//    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:self.playingMusic.icon];
    // 设置持续时间（歌曲的总时间）
    info[MPMediaItemPropertyPlaybackDuration] = self.playingMusic.time;
    // 设置当前播放进度
    info[MPNowPlayingInfoPropertyElapsedPlaybackTime] = @(self.mpc.currentPlaybackTime);
    
    // 切换播放信息
    center.nowPlayingInfo = info;
    
    // 远程控制事件 Remote Control Event
    // 加速计事件 Motion Event
    // 触摸事件 Touch Event
    
    // 开始监听远程控制事件
    // 成为第一响应者（必备条件）
    [self becomeFirstResponder];
    // 开始监控
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

#pragma mark - 远程控制事件监听
- (BOOL)canBecomeFirstResponder
{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    //    event.type; // 事件类型
    //    event.subtype; // 事件的子类型
    //    UIEventSubtypeRemoteControlPlay                 = 100,
    //    UIEventSubtypeRemoteControlPause                = 101,
    //    UIEventSubtypeRemoteControlStop                 = 102,
    //    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    //    UIEventSubtypeRemoteControlNextTrack            = 104,
    //    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    //    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    //    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    //    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    //    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self playDown:nil];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            [self nextDown:nil];
            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:
            [self upDown:nil];
            
        default:
            break;
    }
}

@end
